package com.realbrand.net.realbrandpay.ui.activity.login;


import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.realbrand.net.realbrandpay.APP;
import com.realbrand.net.realbrandpay.R;
import com.realbrand.net.realbrandpay.base.BaseActivity;
import com.realbrand.net.realbrandpay.inter.ILogin;
import com.realbrand.net.realbrandpay.ui.activity.shopcar.CheckOutActivity;
import com.realbrand.net.realbrandpay.ui.activity.wallet.set.VerifyMobileActivity;
import com.realbrand.net.realbrandpay.ui.activity.wallet.WalletActivity;
import com.realbrand.net.realbrandpay.ui.activity.shopcar.ShopCarActivity;
import com.realbrand.net.realbrandpay.ui.activity.wallet.set.WalletLogoutActivity;
import com.realbrand.net.realbrandpay.untils.Constant;
import com.realbrand.net.realbrandpay.api.HTTPAPI;
import com.realbrand.net.realbrandpay.untils.HttpRequest;
import com.realbrand.net.realbrandpay.untils.Static;
import com.realbrand.net.realbrandpay.zxing.util.L;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2017/5/25.
 */

public class LoginActivity extends BaseActivity implements View.OnClickListener {


    @BindView(R.id.use_name)
    EditText useName;
    @BindView(R.id.use_password)
    EditText usePassword;
    @BindView(R.id.bt_fastRegist)
    Button btFastRegist;
    @BindView(R.id.bt_phoneLogin)
    Button btPhoneLogin;
    @BindView(R.id.bt_login)
    Button btLogin;
    @BindView(R.id.bt_forgetPassword)
    Button btForgetPassword;
    @BindView(R.id.login_bt_back)
    ImageView loginBtBack;

    private String et_userName;
    private String et_password;

    private JSONObject object = null;

    //登录状态：true表示已登录 false表示未登录
    public static boolean isLogin = false;


    //用户建行是否已授权
//    public static boolean JianHangIsAuth = false;

    //判断是否是从购物车界面过来

    public static boolean isFormShopCar = false;

    //是否是从包装码界面过来的
    public static boolean isFormPick = false;

    @Override
    protected int getLayoutId() {
        return R.layout.login_activity;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(getLayoutId());
        ButterKnife.bind(this);
        setOnClick();
        //判断是否从购物车过来
        loginBtBack.setVisibility(View.GONE);
        String stringExtra = getIntent().getStringExtra(Constant.formShopCar);
        if (stringExtra != null) {
            if (stringExtra.equals(Constant.formShopCar)) {
                isFormShopCar = true;
                isFormPick = false;
                loginBtBack.setVisibility(View.VISIBLE);
            } else if (stringExtra.equals("pick")) {
                isFormPick = true;
            } else {
                isFormPick = false;
                isFormShopCar = false;
                loginBtBack.setVisibility(View.GONE);
            }
        } else {
            isFormShopCar = false;
            loginBtBack.setVisibility(View.GONE);
        }
    }

    private void initData() {
        Log.d("zhu", "用户名：" + et_userName + "密码：" + et_password);
        object = new JSONObject();
        try {
            object.put("METHOD", "UserLogin");
            object.put("SOURCE", "LoginActivity");
            object.put("CREDENTIALS", "0");
            object.put("TERMINAL", "0");
            object.put("INDEX", Static.getDay());
            if (Static.isMobileNO(et_userName)) {
                //如果是手机号
                object.put("UserAccount", "");
                object.put("UserPasswd", et_password);
                object.put("UserMobile", et_userName);
            } else {
                //如果是用户名
                object.put("UserAccount", et_userName);
                object.put("UserPasswd", et_password);
                object.put("UserMobile", "");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    /**
     * 设置点击事件
     */

    protected void setOnClick() {
        btFastRegist.setOnClickListener(this);
        btForgetPassword.setOnClickListener(this);
        btLogin.setOnClickListener(this);
        btPhoneLogin.setOnClickListener(this);
        loginBtBack.setOnClickListener(this);
    }

    /**
     * 管理按钮点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_phoneLogin:
                startActivity(new Intent(this, PhoneLoginActivity.class));
                finish();
                break;
            //点击登录
            case R.id.bt_login:
                //获取用户输入的手机号码跟密码
                et_userName = useName.getText().toString();
                et_password = usePassword.getText().toString();
                if (TextUtils.isEmpty(et_userName)) {
                    Static.toast(this, "请输入账号或手机号");
                } else if (TextUtils.isEmpty(et_password)) {
                    Static.toast(this, "请输入密码");
                } else {
                    initData();
                    request(object.toString());
                }
                break;
            case R.id.bt_fastRegist:
                startActivity(new Intent(this, RegistActivity.class));
                finish();
                break;
            case R.id.bt_forgetPassword:
                startActivity(new Intent(this, VerifyMobileActivity.class));
                finish();
                break;
            case R.id.login_bt_back:
                startActivity(new Intent(this, ShopCarActivity.class));
                finish();
                break;
            default:
                break;
        }
    }

    /**
     * 登录请求
     *
     * @param json
     */
    private void request(String json) {
        RequestBody body = RequestBody.create(HTTPAPI.JSON, json);
        ILogin iLogin = HttpRequest.request_BASE_URL(ILogin.class);
        Call<ResponseBody> login = iLogin.login(body);
        login.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    if (response.body() == null) {
                        Static.toast(LoginActivity.this, "网络繁忙，请稍后再试");
                    } else {
                        String result = response.body().string();
                        Log.d("zhu", "返回的json字符串" + result);
                        JSONObject jsonObject = new JSONObject(result);
                        String credentials = jsonObject.getString("CREDENTIALS");
                        JSONArray data = jsonObject.getJSONArray("DATA");
                        JSONObject js = data.getJSONObject(0);
                        String result1 = js.getString("result");
                        Log.d("zhu", "返回结果是：" + result1);
                        //判断登录返回结果
                        if ("登录成功！".equals(result1)) {
                            String account = js.getString("UserAccount");
                            String mobile = js.getString("UserMobile");
                            String balance = js.getString("UserBalance");
                            String avatar = js.getString("UserAvatar");
                            String addresseeName = js.getString("AddresseeName");
                            String telephone = js.getString("Telephone");
                            String province = js.getString("Province");
                            String regionCity = js.getString("RegionCity");
                            String countyDistrict = js.getString("CountyDistrict");
                            String detailedAddress = js.getString("DetailedAddress");
                            String strCode = js.getString("qrCode");
                            String userType = js.getString("UserType");
                            //获取当前时间戳
                            long loginTime = Static.timeNow();
                            //存储用户信息
                            Static.saveMassage(LoginActivity.this, account, mobile, balance, avatar, addresseeName,
                                    telephone, province, regionCity, countyDistrict, detailedAddress, strCode, userType, credentials, loginTime);
                            //登录成功，如果是从购物车界面过来就跳转到结算界面，其他就跳转到钱包界面
                            isLogin = true;
                            //用户已授权的数据
                            JSONArray bankName = js.getJSONArray("BankName");
                            JSONArray payAccount = js.getJSONArray("PayAccount");
                            JSONArray name = js.getJSONArray("UserName");
                            SharedPreferences preferences = getSharedPreferences("userMassage", MODE_PRIVATE);
                            SharedPreferences.Editor editor = preferences.edit();
                            if (bankName.length() != 0) {
                                for (int i = 0; i < bankName.length(); i++) {
                                    if (bankName.getString(i).equals("微信")) {
                                        APP.WXIsAuth = true;
                                        String WXAccount = payAccount.getString(i);
                                        String WXName = name.getString(i);
                                        editor.putString("WX", WXAccount);
                                        editor.putString("WXName", WXName);
                                        editor.commit();
                                    } else if (bankName.getString(i).equals("支付宝")) {
                                        APP.AlipayIsAuth = true;
                                        String alipayAccount = payAccount.getString(i);
                                        String alipayName = name.getString(i);
                                        editor.putString("alipay", alipayAccount);
                                        editor.putString("alipayName", alipayName);
                                        editor.commit();
                                    }
//                                    } else if (bankName.getString(i).equals("龙支付")) {
//                                        JianHangIsAuth = true;
//                                        String jianHangAccount = payAccount.getString(i);
//                                        String jianHangName = name.getString(i);
//                                        editor.putString("jianhang", jianHangAccount);
//                                        editor.putString("jianhangName", jianHangName);
//                                        editor.commit();
//                                    }
                                }
                            }
                            if (isFormShopCar) {
                                finish();
                            } else if (isFormPick) {
                                finish();
                            } else {
                                startActivity(new Intent(LoginActivity.this, WalletActivity.class));
                                finish();
                            }
                        } else if ("用户名不存在！".equals(result1)) {
                            Static.toast(LoginActivity.this, "账号不存在");
                        } else if ("用户密码错误！".equals(result1)) {
                            Static.toast(LoginActivity.this, "密码错误");
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    L.d(L.TAG, "登录异常" + e.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                    L.d(L.TAG, "登录异常" + e.toString());
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.d("zhu", "请求失败" + t.toString());
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //返回事件
            startActivity(new Intent(this, WalletLogoutActivity.class));
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }
}
